from glowdrop import settings
from django.utils.translation import ugettext as _
from django.http import HttpResponse
from django.contrib.sessions.backends.db import SessionStore
from django.contrib.auth.models import User
import pprint

def get_notes_range(page_no):
    """get notes' range in a given page
    """
    return [settings.NOTES_PER_PAGE * i for i in (page_no, page_no+1)]

def get_location(request):
    return None

class Question:

    def __init__(self, id=None):
        if id == None:
            self.id = 1
        else:
            self.id = id
        self.q = _("Does Shanghai belong to china?(yes or no)")
        self.a = _("yes")
    
    def __unicode__(self):
        return self.q

    def __str__(self):
        return self.q

    __repr__ = __str__

def login_required_api(func):

    def actual_decorator(request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponse(content="FORBIDDEN\r\n\r\n", status=403)
        else:
            return func(request, *args, **kwargs)

    return actual_decorator

def auth_required_api(func):
    
    def actual_decorator(request, *args, **kwargs):
        if not request.user.is_authenticated():
            try:
                session_key = request.REQUEST["session_key"]
            except KeyError:
                return HttpResponse(content="FORBIDDEN\r\n\r\n", status=403)
            session = SessionStore(session_key=session_key)
            try:
                request.user = User.objects.get(pk=session['_auth_user_id'])
            except KeyError:
                return HttpResponse(content="FORBIDDEN\r\n\r\n", status=403)
        return func(request, *args, **kwargs)

    return actual_decorator


def adjust_avatar(avatar):
    """ if avatar is null, return the default avatar
    """
    if not avatar:
        return settings.DEFAULT_AVATAR_LINK
    else:
        return avatar.url

def trace(s):
    if settings.TRACABLE:
        pprint.pprint(s)

